package com.suncky.frame.utils.activityresult;

import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import java.util.HashMap;
import java.util.Map;

/**
 * author： gl
 * time： 2021/4/9 14:41
 * description：activity result 中间处理类
 */
public class ActivityResultFragment extends Fragment {
    private final Map<Integer, ActivityResultHelper.ActivityResultCallback> callbacks = new HashMap<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    public void startForResult(Intent intent, int requestCode, ActivityResultHelper.ActivityResultCallback callback) {
        callbacks.put(requestCode, callback);
        startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        ActivityResultHelper.ActivityResultCallback callback = callbacks.remove(requestCode);
        if (callback != null) {
            callback.onActivityResult(requestCode, resultCode, data);
        }
    }
}
